<template>
    <Modal
        :value="showModal"
        title="发送文件"
        class-name="upload-dialog"
        @on-cancel="handleCancel">
        <Progress class="position-progress" v-show="showProgress" :percent="percent" :stroke-width="4" hide-info></Progress>
        <Form ref="form" :model="form" :rules="ruleValidate" :label-width="80" :hide-required-mark="true">
            <FormItem prop="title" label="文件标题">
                <Input v-model="form.title"  placeholder="请输入文件标题" />
            </FormItem>
            <FormItem prop="fileName">
                <Row>
                    <Col span="18" class="padding-0">
                        <Input v-model="form.fileName" :readonly="true" placeholder="请选择文件" />
                    </Col> 
                    <Col span="6" class="padding-right-0 padding-left-14">
                        <Upload 
                            ref="upload"
                            action="/upload/file"
                            :show-upload-list="false"
                            :before-upload="handleBeforeUpload">
                            <Button type="primary">选择文件</Button>
                        </Upload>
                    </Col> 
                </Row>
            </FormItem>
            <FormItem prop="targetUserIds" label="接收人">
                <member-tree v-model="form.targetUserIds"></member-tree>
            </FormItem>
            <FormItem label="备注">
                <Input v-model="form.content" type="textarea" :autosize="{minRows: 3,maxRows: 5}" placeholder="请输入备注"></Input>
            </FormItem>
        </Form>
        <div slot="footer">
            <Button type="primary" class="margin-right-25" @click="handleSubmit('form')">提交</Button>
            <Button @click="handleCancel">取消</Button>
        </div>
    </Modal>
</template>

<script>
import { axios } from '@/common/apis/config'
import MemberTree from '@/components/MemberTree'
import { sendFileMessageRest } from '@/common/apis/system'
const CancelToken = axios.CancelToken

export default {
    name: 'uploadFile',
    props: ['showModal'],
    components: {
        MemberTree
    },
    data() {
        return {
            showProgress: false,
            percent: 0,
            userList: [],
            form: {
                title: '',
                fileName: '',
                targetUserIds: [],
                content: ''
            },
            ruleValidate: {
                title: [
                    { required: true, message: '文件标题不能为空', trigger: 'blur' }
                ],
                fileName: [
                    { required: true, message: '文件不能为空', trigger: 'change' }
                ],
                targetUserIds: [
                    { required: true, type: 'array', message: '接收人不能为空', trigger: 'change' }
                ]
            }
        }
    },
    mounted() {

    },
    methods: {
        onChangeUserIds(val) {
            this.$nextTick(() => {
                this.form.targetUserIds = val
                this.$refs.form.validateField('targetUserIds')
            })
        },
        handleSubmit(name) {
            const THIS = this
            this.$refs[name].validate((valid) => {
                if (valid) {
                    if (this.file.size > 10 * 1024 * 1024) {
                        this.$Message.error({
                            background: true,
                            content: '文件大小不能超过10M'
                        })
                        return
                    }

                    this.showProgress = true
                    const formData = new FormData()
                    formData.append('file', this.file)
                    formData.append('type', 1)

                    axios.post(`/upload/file`, formData, 
                        {
                            headers: { 'Content-Type': 'multipart/form-data' },
                            onUploadProgress: this.handleUploadProgress,
                            cancelToken: new CancelToken(function executor(c) {
                                THIS.cancel = c
                            })
                        })
                        .then(uploadResult => {
                            if (uploadResult.data.code === 200) {
                                const fileSHA1 = uploadResult.data.content.sha1
                                // eslint-disable-next-line
                                const { fileName, ...other } = this.form
                                const params = {
                                    ...other,
                                    fileSHA1
                                }
                                sendFileMessageRest(params).then(result => {
                                    if (result.data.code === 200) {
                                        this.handleUploadSuccess()
                                    } else {
                                        this.handleUploadError(result.data.msg)
                                    }
                                })
                            } else {
                                this.handleUploadError()
                            }
                        })
                        .catch(() => {
                            this.handleUploadError()
                        })
                }
            })
        },
        handleBeforeUpload(file) {
            this.file = file
            this.form.fileName = file.name
            return false
        },
        handleUploadProgress(event) {
            this.percent = Math.floor((event.loaded * 100) / event.total)
        },
        handleUploadSuccess(msg) {
            this.$emit('closeUploadModal')
            this.reset()
            this.hideProgress()
            this.$Message.success({
                background: true,
                content: msg || '文件发送成功'
            })
        },
        handleUploadError(msg) {
            this.reset()
            this.hideProgress()
            this.$Message.error({
                background: true,
                content: msg || '文件发送失败'
            })
        },
        handleCancel() {
            this.cancel && this.cancel()
            this.reset()
            this.hideProgress()
            this.$emit('closeUploadModal')
        },
        reset() {
            this.form = {
                title: '',
                fileName: '',
                targetUserIds: [],
                content: ''
            }
            this.$refs.form.resetFields()
            this.$refs.upload.clearFiles()
        },
        hideProgress() {
            this.showProgress = false
        }
    }
}
</script>
